package top.yaofengqiao.springcloudsimple.auth.biz.domain.security.service;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import top.yaofengqiao.springcloudsimple.auth.biz.domain.auth.service.IPermissionService;
import top.yaofengqiao.springcloudsimple.auth.biz.domain.security.model.UserInfo;
import top.yaofengqiao.springcloudsimple.auth.biz.domain.user.model.entity.UserEntity;
import top.yaofengqiao.springcloudsimple.auth.biz.domain.user.service.IUserService;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author yfq
 * @date 2024/5/31 15:07
 * @description 系统管理员认证
 */
@Component
public class AdminUserDetailService implements UserDetailsService {
    @Resource
    private IUserService userService;
    @Resource
    private IPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 查询用户信息
        UserEntity userEntity = userService.queryByUsername(username);

        UserInfo userInfo = buildUserInfo(userEntity);

        if (userInfo == null) throw new UsernameNotFoundException("用户名或密码错误");

        // 2. 查询角色信息
        List<String> roles = permissionService.queryRoles(userInfo.getUserId());
        userInfo.setRoles(roles);

        return userInfo;
    }

    private UserInfo buildUserInfo(UserEntity userEntity) {
        if (userEntity == null) return null;

        return UserInfo.builder()
                .userId(userEntity.getId())
                .username(userEntity.getUsername())
                .password(userEntity.getPassword())
                .status(userEntity.getStatus())
                .mobile(userEntity.getMobile())
                .icon(userEntity.getAvatar())
                .build();
    }

}
